import axios from 'axios'


export function createHttpClient(accessToken) {
  const instance = axios.create({
    baseURL: '',
    headers: {
      'Cache-Control': 'no-cache',
      'Content-Type': 'application/json;charset=utf-8',
      accessToken: accessToken || null,
    },
    timeout: 10000,
    withCredentials: true,
  });
  // axios.defaults.timeout = 10000
  // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data'

  // 请求拦截器
  instance.interceptors.request.use(
    config => {
      return config
    },
    error => {
      console.log(error)
      return Promise.error(error)
    })

  // 响应拦截器
  instance.interceptors.response.use(
    response => {
      if (response.status === 200) {
        return Promise.resolve(response, response.status)
      } else {
        return Promise.reject(response)
      }
    },
    // 服务器状态码不是200的情况
    error => {
      console.log(error.response.status)
      if (error.response.status) {
        return Promise.reject(error.response)
      }
    }
  )
  return new HttpClient(instance)
}

export class HttpClient {
  constructor(instance) {
    this.instance = instance;
  }
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err.data)
        })
    })
  }
}


/**
 * request
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// export function request(url, params) {
//   return new Promise((resolve, reject) => {
//     instance.request(url, params)
//       .then(res => {
//         resolve(res.data)
//       })
//       .catch(err => {
//         reject(err.data)
//       })
//   })
// }

